
from project.crawler.mukeCrawler import url_manager, html_downloader, html_parser, html_output
class spiderMain():

    def __init__(self):
        print("spiderMain")
        self.urls = url_manager.url_Manager()
        self.downloader = html_downloader.html_Downloader()
        self.parser = html_parser.HtmlParser()
        self.outputer = html_output.HtmlOutputer()

    def crawler(self, root_url):
        print("爬取初始地址：" + root_url)
        print("开始爬取")
        count = 1   # url计数
        # 添加根url
        self.urls.add_new_url(root_url)
        # 开始解析
        while self.urls.has_new_url():
            try:
                # 获取url
                new_url = self.urls.get_new_url()
                print("第%d个url：%s" % (count, new_url))
                # 将url对应的页面进行下载
                html_cont = self.downloader.download(new_url)
                # 对下载下来的页面进行解析,将解析出来的数据进行保存
                new_urls, new_data = self.parser.parse(new_url, html_cont)
                # 将解析出来的urls添加到url_manager
                self.urls.add_new_urls(new_urls)
                # 将数据进行收集
                self.outputer.collect_data(new_data)

                if count == 15:
                    break
                count += 1
            except:
                print("爬取失败")

        self.outputer.output_html()

if __name__ == "__main__":
    root_url = "http://baike.baidu.com/view/21087.htm"
    spider = spiderMain()
    spider.crawler(root_url)